import { TabbarPageEnum } from "@/enums/PageEnum";
import { getUrl } from "@/router";
import { type QueryType } from "@/router/types";
import { type CustomNavigateToOptions } from "@/router/types/nav";
import { type PagesType } from "@/router/types/pages";
import { useUserStoreWithOut } from "@/store/modules/user";
import { forIn, isObject } from "lodash-es";

/**
* @description 创建一个url参数
* @date 15/11/2023
* @param {Recordable} query
*/
export function createShareQueryStr(query: Recordable) {
  const { userInfo } = useUserStoreWithOut()
  let queryStr = ''
  const shareKeyStr = 'shareKey'
  forIn(query, (value, key) => {
    if (value && key !== shareKeyStr) queryStr += `${key}=${query[key]}&`
  });
  queryStr += `${shareKeyStr}=${userInfo.shareKey}`
  return queryStr
}

/**
 * @description 创建一个分享参数
 * @date 02/08/2024
 * @param {Recordable} query
 */
export function createShareQuery(query: Recordable): Recordable {
  const { userInfo } = useUserStoreWithOut()
  return {
    ...query,
    shareKey: userInfo.shareKey
  }
}

export function useAppShare() {
  /**
   * @description 重定向分享路径
   * @date 14/11/2023
   * @export
   * @template T
   * @param {CustomNavigateToOptions<T>} op
   */
  function setWxSharePath<T extends PagesType>(op: CustomNavigateToOptions<T>) {
    const path = op.name
    let options = !isObject(op.options) ? {} : op.options
    let str = JSON.stringify(createShareQuery(options))
    if (!path) {
      throw '【setWxSharePath】==> 请传入正确的路由名';
    }
    const startPage = getUrl(TabbarPageEnum.STARTPAGE, {
      path,
      ...(str && { query: str }),
    });
    return decodeURIComponent(startPage);
  }

  /**
 * @description 设置微信分享朋友圈参数
 * @date 14/11/2023
 * @export
 * @param {QueryType} query
 * @returns {string}
 */
  function setWxShareTimelineQuery(query: QueryType): string {
    return createShareQueryStr({ ...query })
  }


  return {
    setWxSharePath,
    createShareQuery,
    createShareQueryStr,
    setWxShareTimelineQuery,
  }
}